//
//  QLPublishCircleFriendsVC.m
//  神约
//
//  Created by qlwl on 16/12/16.
//  Copyright © 2016年 qlwl. All rights reserved.
//

#import "QLPublishCircleFriendsVC.h"
#import "UIView+FrameKIt.h"
#import "UIAlertController+AlertController.h"
#import "QLPublishCircleFirendsCell.h"
#import "WhoCanSeeVC.h"
#import "QLChooseLocationVC.h"
#import "WYVideoCompressTools.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>


#define NumOfPerLine 3
#define ResouceWidth 70 * ScreenWidthScale
#define Space 8

@interface QLPublishCircleFriendsVC ()<UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *placehoderLab;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutCollHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutCollWidth;
@property (nonatomic, assign) WhoCanSeeType seeType ; //

//@property (nonatomic, copy) NSString * cityName ; //
//@property (nonatomic, assign) CLLocationCoordinate2D coor2D ; //
//@property (nonatomic, copy) NSString * address ; //
@property (nonatomic, strong) AMapPOI * poi ; //
@property (nonatomic, assign) int recordCount ; //
@end

@implementation QLPublishCircleFriendsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self getMyNavBarWithNavTitle:@"" andLeftBtnTitle:@"取消" andLeftIma:nil andRightTitle:@"发布" andRightIma:nil and:^(int tag) {
        if (tag == 1) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            [self publishText];
        }
    }];
    
    [self setNavBarColor:NavBarTintColor];
    
    [self addObserver:self forKeyPath:@"resouceArray" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    ((UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout).minimumLineSpacing = Space;
    ((UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout).minimumInteritemSpacing = Space;
    
    if (self.resouceArray == nil) {
        self.resouceArray = [[NSMutableArray alloc] init];
    }
//    if (self.resouceType == PublishResouceMedia) {
//        //先转码视频
//        //压缩视频
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            [self compressVideoWithPath:[self changeVideoToMap4WithVideoURL:[NSURL URLWithString:[self.resouceArray firstObject]]]];
//        });
//    }
    [self reloadTabHeightByItemCount:self.resouceArray.count];
   
    
}

#pragma mark 
//- (NSMutableArray *)resouceArray
//{
//    if (_resouceArray == nil) {
//        _resouceArray = [[NSMutableArray alloc] init];
//    }
//    return _resouceArray;
//}

- (void)resouceArrayAddObjec:(id)obj
{
    [[self mutableArrayValueForKey:@"resouceArray"] addObject:obj];
    // 对于改变数组个数的操作都要用[self mutableArrayValueForKey:@"resouceArray"]方法获取该数组
}
- (void)reloadTabHeightByItemCount:(NSInteger)count
{
    if (count<9) {
        count = count + 1;
    }
    int lineCount = (int)(count%NumOfPerLine == 0?count/NumOfPerLine:count/NumOfPerLine+1);
    if (count == 0) {
        lineCount = 1;
    }
    float collWidth = (ResouceWidth+Space)*NumOfPerLine - Space + 1;
    float collHeight = lineCount * (ResouceWidth+Space) - Space + 1;
    
    self.tableView.tableHeaderView.f_height = self.tableView.tableHeaderView.f_height - self.layoutCollHeight.constant + collHeight;
    self.layoutCollWidth.constant = collWidth;
    self.layoutCollHeight.constant = collHeight;
}
#pragma mark observe
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"resouceArray"]) {
        //刷新高度
        [self reloadTabHeightByItemCount:self.resouceArray.count];
        [self.collectionView reloadData];
    }
}
- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"resouceArray"];
}

#pragma mark TabDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QLPublishCircleFirendsCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QLPublishCircleFirendsCell"];
    if (indexPath.row == 0) {
        cell.imageView.image = [UIImage imageNamed:@"publishCircle位置"];
        cell.textLabel.text = @"位置";
        cell.conLab.text = self.poi.address;
    }else{
        cell.imageView.image = [UIImage imageNamed:@"publishCircle看充"];
        cell.textLabel.text =  @"谁可以看";
        cell.conLab.text = @[@"公开",@"关注",@"秘密"][self.seeType];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 1) {
        WhoCanSeeVC * seeVC = [NSString instantiateViewControllerWithIdentifier:@"WhoCanSeeVC" andSBName:@"Discover"];
        seeVC.seeType = self.seeType;
        seeVC.finishSelectSeeType = ^(WhoCanSeeType seeType){
            self.seeType = seeType;
            [tableView reloadData];
        };
        [self.navigationController pushViewController:seeVC animated:YES];
    }else if (indexPath.row == 0){
        QLChooseLocationVC * locatVC = [NSString instantiateViewControllerWithIdentifier:@"QLChooseLocationVC" andSBName:@"Discover"];
        locatVC.selectLocationAddress = ^(AMapPOI * poi){
            self.poi = poi;
            [self.tableView reloadData];
        };
        [self.navigationController pushViewController:locatVC animated:YES];
    }
}

#pragma mark CollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.resouceType == PublishResoucePic) {
        return self.resouceArray.count + 1;
    }else{
        return self.resouceArray.count ;
    }
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    QLPublishCircleFriendsCollCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"QLPublishCircleFriendsCollCell" forIndexPath:indexPath];
    
    if (self.resouceType == PublishResoucePic) {
        if (indexPath.row == self.resouceArray.count) {
            cell.bgImaView.image = [UIImage imageNamed:@"publishAddResouce"];
            cell.deleteBtn.hidden = YES;
        }else{
            cell.bgImaView.image = self.resouceArray[indexPath.row];
            cell.deleteBtn.hidden = NO;
            cell.deleteIma = ^{
                [self.resouceArray removeObjectAtIndex:indexPath.row];
                [self.collectionView reloadData];
            };
        }
        cell.playBtn.hidden = YES;
    }else{
        cell.bgImaView.image = [self getVideoImaWithUrl:[NSURL fileURLWithPath:self.resouceArray[indexPath.row]]];
        cell.deleteBtn.hidden = YES;
        cell.playBtn.hidden = NO;
        cell.playVideo = ^(void){
            [self playPlayerWithMovieStr:self.resouceArray[indexPath.row]];
        };
    }
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(ResouceWidth, ResouceWidth);
    
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,0,0,0);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.resouceArray.count) {
        if (self.resouceType == PublishResoucePic) {
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet andCancelAction:^{
                
            } andOtherAction:^(int tag) {
                [self selectImaWithType:PickerCameraSourceType + tag];
            } cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从手机相册选择",nil];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            // 直接录像
        }
    }else{
        
    }
}
- (BOOL) shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    self.placehoderLab.hidden = textView.text.length;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.textView resignFirstResponder];
}
#pragma mark PickerController 相机相册
- (void)finishImagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info andType:(PickerControllerSourceType)type andMediaURL:(NSURL *)url
{
    if (type==PickerVideoSourceType) {
        
    }else if (type==PickerAlbumSourceType||type==PickerCameraSourceType){
        NSMutableArray *picArray=[[NSMutableArray alloc] init];
        [picArray addObject:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
        [[self mutableArrayValueForKey:@"resouceArray"] addObjectsFromArray:picArray];
    }
}
- (void)finishAssetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSMutableArray *)picArray
{
    //图片
}
- (void)failImagePickerControllerDidCancel:(UINavigationController*)picker
{
    
}

////压缩视频,中等质量视频压缩
//- (void)compressVideoWithPath:(NSString *)path
//{
//    [WYVideoCompressTools compressVideoWithSourceVideoPathString:[self.resouceArray firstObject] CompressType:AVAssetExportPresetMediumQuality CompressSuccessBlock:^(NSString *compressVideoPathString) {
//        if (compressVideoPathString) {
//            //self.compressFile = compressVideoPathString;
//        }
//        [self removeVideoWithVideoPath:path];
//    } CompressFailedBlock:^{
////        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"视频压缩失败了!" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
////        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:nil];
////        [alertController addAction:confirmAction];
////        [self presentViewController:alertController animated:YES completion:nil];
//        [self removeVideoWithVideoPath:path];
//    } CompressNotSupportBlock:^{
////        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"不支持当前压缩格式哦!" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
////        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:nil];
////        [alertController addAction:confirmAction];
////        [self presentViewController:alertController animated:YES completion:nil];
//        [self removeVideoWithVideoPath:path];
//    }];
//}
// 播放本地的视频
- (void)playPlayerWithMovieStr:(NSString *)movStr
{
    MPMoviePlayerViewController *playerVC=[[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:movStr]];
    [playerVC.moviePlayer prepareToPlay];
    [self presentViewController:playerVC animated:YES completion:nil];
}

#pragma mark 发布圈子接口
- (void)publishText
{
    QLLoginModel * loginModel = [QLLoginModel accountFromSandbox];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"userid"] = loginModel.userId;
    postDict[@"content"] = self.textView.text;
    postDict[@"canseetype"] = [NSNumber numberWithInteger:self.seeType];
    postDict[@"cityname"] = self.poi.city;
    if (self.poi) {
        postDict[@"longitude"] = [NSString stringWithFormat:@"%f",self.poi.location.longitude];
        postDict[@"latitude"] = [NSString stringWithFormat:@"%f",self.poi.location.latitude];
        postDict[@"address"] = self.poi.address;
    }
    [QLNetWorking postJSONWithUrl:QLPublishCircleSaveTextURL parameters:postDict isJosnRequest:YES rogress:nil success:^(id result) {
        NSLog(@"%@",result);
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
//            NSString * json = [[result objectForKey:@"mobileBody"] objectForKey:@"data"];
//            id obj = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            NSString * dynamicid = [[[result objectForKey:@"mobileBody"] objectForKey:@"data"] objectForKey:@"id"];
            if (self.resouceArray.count == 0) {
                if (self.publishFinishAndRefresh) {
                    self.publishFinishAndRefresh();
                }
                [LPPopup showInCenterOfWindowWithText:@"发布成功" completion:nil];
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                return ;
            }
            if (self.resouceType == PublishResoucePic) {
                [self publishImaWithArray:self.resouceArray andDynamicid:dynamicid];
            }else{
                [self publishVideoWithFile:[self.resouceArray firstObject] andDynamicid:dynamicid];
            }
        }else{
            [LPPopup showInCenterOfWindowWithText:[[result objectForKey:@"mobileHead"] objectForKey:@"message"] completion:nil];
        }
    } fail:^(NSError *error) {
        
    }];
    
}
// 发布图片
- (void)publishImaWithArray:(NSArray <UIImage *>*) imaArray andDynamicid:(NSString *)dynamicid
{

    self.recordCount = 0;
    for (UIImage * ima in imaArray) {
        [self publishNetImaWithIma:ima andDynamicid:dynamicid andAllResouceCount:(int)imaArray.count];
    }
}
- (void)publishNetImaWithIma:(UIImage *)ima andDynamicid:(NSString *)dynamicid andAllResouceCount:(int)count
{
    if (!ima) {
        return;
    }
    if (dynamicid.length == 0) {
        return;
    }
    QLLoginModel * loginModel = [QLLoginModel accountFromSandbox];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"userid"] = loginModel.userId;
    postDict[@"id"] = dynamicid;
    postDict[@"type"] = @"4";
    [QLNetWorking upImaWithURL:QLPublishLifeInvitImaURL parameters:postDict fieldName:@"file" andImas:@[ima] success:^(id result) {
        NSLog(@"%@",result);
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
            self.recordCount ++;
            if (count == self.recordCount) {
                if (self.publishFinishAndRefresh) {
                    self.publishFinishAndRefresh();
                }
                [LPPopup showInCenterOfWindowWithText:@"发布成功" completion:nil];
                [self dismissViewControllerAnimated:YES completion:nil];
                
            }
        }
    } fail:^(NSError *error) {
        
    }];
}
//发布视频
- (void)publishVideoWithFile:(NSString *)videoFile andDynamicid:(NSString *)dynamicid
{
    if (videoFile.length == 0) {
        return;
    }
    if (dynamicid.length == 0) {
        return;
    }
    QLLoginModel * loginModel = [QLLoginModel accountFromSandbox];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"userid"] = loginModel.userId;
    postDict[@"id"] = dynamicid;
    postDict[@"type"] = @"1";
    [QLNetWorking upFileWithURL:QLPublishLifeInvitVideoURL parameters:postDict isJosnRequest:YES constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:videoFile] name:@"file" error:nil];
//        [formData appendPartWithFileData:[NSData dataWithContentsOfFile:videoFile] name:@"file" fileName:[NSString stringWithFormat:@".%@",[[NSURL fileURLWithPath:videoFile] pathExtension]] mimeType:@"video/quicktime"];
        UIImage *ima = [self getVideoImaWithUrl:[NSURL fileURLWithPath:videoFile]];
        NSData *imaData=UIImageJPEGRepresentation(ima, 1);
        NSString *imaName = [NSString stringWithFormat:@"%@.png",dynamicid];
        [formData appendPartWithFileData:imaData name:@"videopic" fileName:imaName mimeType:@"image/jpeg"];
    } progress:nil success:^(id result) {
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
            if (self.publishFinishAndRefresh) {
                self.publishFinishAndRefresh();
            }
            [LPPopup showInCenterOfWindowWithText:@"发布成功" completion:nil];
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            [WYVideoCompressTools deleteCompressVideoFromPath:videoFile];
        }
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}


@end
